package crontab

import (
	"github.com/robfig/cron/v3"
	"sync"
)

type Crontab struct {
	Spec string
	Func func()
}

var cronEngine *cron.Cron

var Crontabs []Crontab

var once sync.Once

func init() {
	once.Do(func() {
		cronEngine = cron.New(cron.WithSeconds())
	})
}

func Add(spec string, cmd func()) {
	crontab := Crontab{
		Spec: spec,
		Func: cmd,
	}
	Crontabs = append(Crontabs, crontab)
}

func Run() {
	if len(Crontabs) <= 0 {
		return
	}
	for _, tab := range Crontabs {
		cronEngine.AddFunc(tab.Spec, tab.Func)
	}
	cronEngine.Start()
	select {}
}
